<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use EasyWeChat;
use Log;

class WechatPushOrderEndedMsg implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order;

    /**
     * Create a new job instance.
     *
     * @param $order
     */
    public function __construct($order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (!empty($this->order) && !empty($this->order->user->wx_official_open_id)) {
            $wechat = EasyWeChat::officialAccount();

            $data = [
                'title' => "您本次充电已结束",
                'keyword1' =>  $this->order->order_sn,
                'keyword2' =>  $this->order->device_address,
                'keyword3' =>  $this->order->service_start_at->format('m月d日 h:i') . ' ~ ' . $this->order->service_start_at->format('m月d日 h:i'),
                'keyword4' => $this->order->consume_duration . ' 分钟',
                'keyword5' => $this->order->real_pay_money . ' 元',
                'remark' => '感谢您的使用！',
            ];

            $pay_score = 0;
            if ($this->order->real_pay_money == 0) {
                foreach ($this->order->payments as $payment) {
                    if ($payment->pay_mode == 'score') {
                        $pay_score += $payment->money;
                    }
                }

                $data['keyword5'] = $pay_score . '积分';
            }

            $res = $wechat->template_message->send([
                'touser' => $this->order->user->wx_official_open_id,
                'template_id' => 'edOj9ti7kALAW6MhPi6iTOC2X_QArICQHxwcwMAGaDE',
                'data' => $data,
            ]);

            Log::debug('微信推送消息', [$data, $res]);
        }
    }
}
